<template>
  <el-container class="home-sjcxzx" v-loading="loading">
    <el-header class="header" style="margin-bottom: 0">
      <el-form ref="ruleFormRef" class="between-form" :inline="true">
        <div>
          <div class="tab-select border">
            <span
              v-for="(item, index) in tabList"
              class="btn nobg"
              :class="{
                active: currentTab == item.objectId,
                noright: index == tabList.length - 1,
              }"
              @click="selectTab(item.objectId)"
              :key="index"
              >{{ item.tableNameChn }}</span
            >
          </div>
        </div>

        <el-form-item class="mr0">
          <el-button
            type="primary"
            class="search-btn"
            @click="getSearch(ruleFormRef)"
          >
            查询
          </el-button>
          <el-button @click="reset(ruleFormRef)" class="reset-btn"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </el-header>
    <el-header class="header search-header more-header">
      <p class="search-down" @click="showMore">
        <span class="icon-down"
          ><el-icon color="#2263BF"><DArrowLeft /></el-icon
        ></span>
        <span>展开条件{{ formatSearch() }}</span>
      </p>
    </el-header>
    <div class="search-box" v-show="showSearch">
      <SearchForm
        :formList="dataInfo.search"
        v-if="dataInfo.search.length > 0"
        v-model="searchData"
      ></SearchForm>
      <p class="line"></p>
      <div class="close-bottom" @click="showMore(2)">
        <span class="icon-up"
          ><el-icon color="#2263BF"><DArrowLeft /></el-icon
        ></span>
        <span>收起展开项</span>
      </div>
    </div>
    <el-header class="header">
      <div class="header-l">
        <span class="text">共查询到{{ total }}条数据</span>
      </div>
      <div class="header-r">
        <el-button type="primary" class="self_btn" @click="handlerFilter">
          <el-icon><Sort /></el-icon>排序
        </el-button>
        <el-button type="primary" class="self_btn" @click="exportData">
          <el-icon class="el-icon--right"><Upload /></el-icon>导出
        </el-button>
      </div>
    </el-header>
    <el-main>
      <el-container>
        <el-main>
          <el-container>
            <el-main class="container bc-table">
              <TableX
                :tableData="dataInfo.tableData"
                :column="dataInfo.culumn"
              ></TableX>
            </el-main>
            <el-footer class="footer mt20">
              <el-pagination
                v-model:current-page="tableField.pageNo"
                v-model:page-size="tableField.pageSize"
                :page-sizes="[10, 20, 30, 50, 100]"
                layout="sizes, prev, pager, next, jumper"
                :total="total"
                :background="true"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                prev-text="上一页"
                next-text="下一页"
              />
            </el-footer>
          </el-container>
        </el-main>
      </el-container>
    </el-main>
    <!-- 抽屉 -->
    <Detail
      :tableData="dataInfo.tableData"
      :column="fieldList"
      v-if="tableDrawer"
      @exportData="saveExport"
      @close="tableDrawer = false"
    ></Detail>
    <!-- 排序 -->
    <SelfDialog
      :dialogVisable="filterVisable"
      title="排序"
      @close="confirmAdd(1)"
      @confirm="confirmAdd(2)"
    >
      <template #default>
        <div class="px_content">
          <p class="form-header">
            排序规则：若配置多个排序条件，则按设定条件依次执行
          </p>
          <div
            class="form-item-dialog"
            v-for="(item, index) in sortList"
            :key="index"
          >
            <div class="left-select">
              <el-select
                v-model="sortList[index].sortField"
                placeholder="请选择排序字段"
                style="width: 220px"
              >
                <el-option
                  v-for="item in dataInfo.field"
                  :key="item.props"
                  :label="item.label"
                  :value="item.props"
                />
              </el-select>
              <img
                @click="addSelect"
                class="imgicon"
                v-if="index == sortList.length - 1"
                src="../../assets/images/addi.png"
              />
              <img
                @click="deleteItem(index)"
                class="imgicon"
                v-if="sortList.length != 1"
                src="../../assets/images/delte.png"
              />
            </div>
            <div class="right-select">
              <el-radio-group v-model="sortList[index].sortDir">
                <el-radio value="asc">升序</el-radio>
                <el-radio value="desc">降序</el-radio>
              </el-radio-group>
            </div>
          </div>
        </div>
      </template>
    </SelfDialog>
    <!-- 导出 -->
    <SelfDialog
      :dialogVisable="exportVisable"
      title="导出"
      width="540px"
      @close="exportVisable = false"
    >
      <template #default>
        <div class="export_content" v-if="exportVisable">
          <Transfer v-model="fieldList" :fieldList="dataInfo.field"></Transfer>
        </div>
      </template>
      <template v-slot:footer>
        <el-button
          class="cancel-btn"
          @click="showTableDrawer"
          :disabled="fieldList.length === 0"
          >预 览</el-button
        >
        <el-button
          class="confirm-btn"
          type="primary"
          :disabled="fieldList.length === 0"
          @click="saveExport"
        >
          导 出
        </el-button>
      </template>
    </SelfDialog>
  </el-container>
</template>

<script setup>
import axios from "axios";
import { onMounted, ref, reactive } from "vue";
import { useRouter, useRoute } from "vue-router";
import { Minxfun } from "@/utils/minxin";
import eventBus from "@/utils/mitt";
import {
  getObjList,
  getOptionList,
  getallList,
  getSortList,
} from "@/api/sjcxzx";
const { handleSizeChange, handleCurrentChange, tableField, total, loading } =
  Minxfun();
import Detail from "./detail.vue";
import SelfDialog from "@/components/dialog/dialog.vue";
import SearchForm from "./search.vue";
import Transfer from "@/components/transfer/transfer.vue";
import TableX from "@/components/table/table.vue";
const router = useRouter();

let dataInfo = reactive({
  tableData: [],
  culumn: [],
  search: [],
  field: [],
});

const ruleFormRef = ref();
const searchData = ref([]);

const formatSearch = () => {
  let arr = [];

  searchData.value.forEach((item) => {
    if (!item) return;
    if (Array.isArray(item.value) && item.value.length > 0) {
      arr.push(1);
    } else if (!Array.isArray(item.value) && item.value) {
      arr.push(1);
    }
  });
  return arr.length > 0 ? `(已选 ${arr.length})` : null;
};

onMounted(() => {
  getObjListFun();
});

// 获取顶层tab
let currentTab = ref("");
let tabList = ref([]);
const selectTab = (index) => {
  currentTab.value = index;
  getOptions(currentTab.value);
  sortList.value = [
    {
      sortField: "",
      sortDir: "",
    },
  ];
};
const getObjListFun = async () => {
  try {
    loading.value = true;
    let { data } = await getObjList();
    tabList.value = data.objectTableDTOList;
    currentTab.value =
      data.objectTableDTOList[0] && data.objectTableDTOList[0].objectId
        ? data.objectTableDTOList[0].objectId
        : "";
    getOptions(currentTab.value);
    loading.value = false;
  } catch (e) {
    console.error(e);
  }
};

// 获取查询条件

const getOptions = async (id) => {
  try {
    loading.value = true;
    let { data } = await getOptionList({
      objectId: id,
    });
    dataInfo.search = data;
    getSortfield();
    loading.value = false;
  } catch (e) {
    console.error(e);
  }
};

// 获取排序字段

const getSortfield = async () => {
  try {
    // loading.value = true;
    let { data } = await getSortList({
      objectId: currentTab.value,
    });
    dataInfo.field = data.map((item) => {
      return {
        label: item.itemNameChn,
        value: item.itemName,
        props: item.itemName,
      };
    });
    // loading.value = false;
  } catch (e) {
    console.error(e);
  }
};

const getSearch = () => {
  showSearch.value = false;
  if (tableField.value.pageNo == 1) {
    getTableData();
  } else {
    tableField.value.pageNo = 1;
    getTableData();
  }
};

const reset = (ruleFormRef) => {
  searchData.value.forEach((item) => {
    if (Array.isArray(item.value) && item.value.length > 0) {
      item.value = [];
      item.matchOption = "";
    } else if (item.value) {
      item.value = "";
    }
  });
  sortList.value = [
    {
      sortField: "",
      sortDir: "",
    },
  ];
  ruleFormRef.resetFields();
  // getTableData();
  getSearch();
};

watch(tableField, (newvla, oldval) => {
  getTableData();
});

let catchTab = "";
// 查询列表
const getTableData = async () => {
  try {
    loading.value = true;
    let sort = [];
    sortList.value.forEach((item) => {
      if (item.sortField && item.sortDir) {
        sort.push(item);
      }
    });
    let search = [];
    searchData.value.forEach((item) => {
      if (Array.isArray(item.value)) {
        if (item.value.length > 0) {
          search.push(item);
        }
      } else if (item.value) {
        search.push(item);
      }
    });
    let { data } = await getallList({
      objectId: currentTab.value,
      queryOptions: search,
      ...tableField.value,
      pageNum: tableField.value.pageNo,
      orderBys: sort,
    });
    dataInfo.tableData = [];
    if (dataInfo.culumn.length === 0 && catchTab !== currentTab.value) {
      catchTab = currentTab.value;
      let ObjecInfo =
        data.objectDataList.length > 0
          ? JSON.parse(data.objectDataList[0])
          : {};
      for (let key in ObjecInfo) {
        dataInfo.culumn.push({
          props: key,
          label: key,
        });
      }
    }
    if (data.objectDataList.length > 0) {
      data.objectDataList.forEach((element, index) => {
        let item = JSON.parse(element);
        dataInfo.tableData.push(item);
      });
    }

    total.value = data.total;
    loading.value = false;
  } catch (e) {
    loading.value = false;
    console.error(e);
  }
};

let currentRow = ref(null);
let showDetail = ref(false);
const handleClick = (value) => {
  currentRow.value = value;
  showDetail.value = true;
};

let showSearch = ref(true);
const showMore = (value) => {
  showSearch.value = !showSearch.value;
  eventBus.emit("changsewidth");
  if (value == 2) {
    getSearch();
  }
};

// 排序
let filterVisable = ref(false);
let sortList = ref([
  {
    sortField: "",
    sortDir: "",
  },
]);

const addSelect = () => {
  sortList.value.push({
    sortField: "",
    sortDir: "",
  });
};

const deleteItem = (index) => {
  sortList.value.splice(index, 1);
};

// 排序
const handlerFilter = () => {
  if (currentTab.value !== catchTab) {
    sortList.value = [
      {
        sortField: "",
        sortDir: "",
      },
    ];
  }
  filterVisable.value = !filterVisable.value;
};

const confirmAdd = (value) => {
  if (value == 1) {
    filterVisable.value = false;
  } else {
    getSearch();
    filterVisable.value = false;
  }
  console.log(sortList.value);
};

// 导出

const exportVisable = ref(false);
let fieldList = ref([]);
let tableDrawer = ref(false);
const exportData = () => {
  fieldList.value = [];
  exportVisable.value = !exportVisable.value;
};

const saveExport = async () => {
  try {
    // exportVisable.value = false;
    // console.log(fieldList.value);

    let sort = [];
    sortList.value.forEach((item) => {
      if (item.sortField && item.sortDir) {
        sort.push(item);
      }
    });
    let search = [];
    searchData.value.forEach((item) => {
      if (Array.isArray(item.value)) {
        if (item.value.length > 0) {
          search.push(item);
        }
      } else if (item.value) {
        search.push(item);
      }
    });
    let params = {
      objectId: currentTab.value,
      queryOptions: search,
      orderBys: sort,
      selectItems: fieldList.value.map((item) => item.props),
    };
    let config = {
      headers: {
        "Content-Type": "application/json;charset=UTF-8",
        "Access-Control-Allow-Origin": true,
        withCredentials: true,
        "Access-Control-Expose-Headers": "Authorization",
      },
      responseType: "blob",
    };
    axios
      .post("/data-center/query/composite/export", params, config)
      .then((res) => {
        let data = JSON.parse(res.data)
        window.open(data.data.message);
        exportVisable.value = !exportVisable.value;
        // const content = res.data;
        // const blob = new Blob([content]);
        // const fileName =
        //   decodeURI(
        //     res.headers["content-disposition"].split(";")[1].split("=")[1]
        //   ) || "文件.xlsx";
        // if ("download" in document.createElement("a")) {
        //   // 非IE下载
        //   const elink = document.createElement("a");
        //   elink.download = fileName;
        //   elink.style.display = "none";
        //   elink.href = URL.createObjectURL(blob);
        //   document.body.appendChild(elink);
        //   elink.click();
        //   URL.revokeObjectURL(elink.href); // 释放URL 对象
        //   document.body.removeChild(elink);
        // } else {
        //   // IE10+下载
        //   navigator.msSaveBlob(blob, fileName);
        // }
      });
  } catch (e) {}
};

const showTableDrawer = () => {
  tableDrawer.value = true;
};
</script>

<style lang="scss" scoped>
.home-sjcxzx {
  width: 100%;
  height: 100%;
  position: relative;

  .header {
    min-height: 36px;
    line-height: 36px;
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-sizing: border-box;
    overflow: hidden;
    margin-bottom: 18px;
    .header-l {
      display: flex;
      align-items: center;
      .text {
        font-family: PingFangSC, PingFang SC;
        font-weight: 500;
        font-size: 14px;
        color: #666666;
        line-height: 22px;
        letter-spacing: 1px;
        text-align: left;
        padding-left: 14px;
      }
    }
  }
  .container {
  }

  .more-header {
    padding: 0 !important;
    border-radius: 6px;
    .search-down {
      width: 100%;
      text-align: center;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 14px;
      color: #666666;
      line-height: 20px;
      cursor: pointer;
      .icon-down {
        display: inline-block;
        transform: rotate(-90deg);
        margin-right: 8px;
      }
    }
  }
}
.el-container {
  height: 100% !important;
  padding: 0 !important;
}
.el-header {
  height: auto !important;
  min-height: 36px !important;
}
.el-main {
  padding: 0 !important;
}
.search {
  margin: 0 50px;
}
.header-r {
  font-family: PingFangSC, PingFang SC;
  font-weight: 500;
  font-size: 14px;
  color: #666666;
}
.search-box {
  position: absolute;
  width: 100%;
  height: calc(100% - 50px);
  background: #ffffff;
  border-radius: 6px 0px 0px 6px;
  z-index: 2;
  bottom: 0;
  .line {
    width: 100%;
    height: 11px;
    background: #f6f9ff;
    position: absolute;
    bottom: 40px;
  }
  .close-bottom {
    position: absolute;
    bottom: 0;
    height: 40px;
    background: #ffffff;
    box-shadow: 0px 0px 29px 0px rgba(70, 102, 149, 0.06);
    border-radius: 6px;
    width: 100%;
    text-align: center;
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: #666666;
    line-height: 40px;
    cursor: pointer;
    .icon-up {
      display: inline-block;
      transform: rotate(90deg);
      margin-right: 8px;
    }
  }
}

.px_content {
  padding: 0 20px;
  .form-header {
    padding-left: 12px;
    height: 36px;
    background: rgba(142, 191, 255, 0.32);
    border-radius: 3px;
    font-family: PingFangSC, PingFang SC;
    font-weight: 500;
    font-size: 12px;
    color: #2c84ff;
    line-height: 36px;
  }
}

.export_content {
  padding: 0 20px;
}
</style>

<style lang="scss">
.el-form-item__label {
  font-family: PingFangSC, PingFang SC;
  font-weight: 500;
  font-size: 14px;
  color: #333333;
}

.form-item-dialog {
  margin-top: 20px;
  display: flex;
  align-content: center;
  .left-select {
    width: 60%;
    display: flex;
    align-items: center;
  }
  .right-select {
    margin-left: 10px;
    .is-checked {
      .el-radio__inner {
        background: #fff !important;
      }
      .el-radio__inner::after {
        width: 8px;
        height: 8px;
        background: #2263bf;
      }
    }
    .el-radio__inner {
      border: 1px solid #2263bf !important;
    }
    .el-radio__label {
      color: #666666 !important;
    }
  }
  .imgicon {
    width: 20px;
    height: 20px;
    margin-left: 10px;
    cursor: pointer;
  }
}
</style>
